﻿using System;
using System.Web.Mvc;

namespace Caramel.Web.Mvc
{
	public class UnitOfWorkAttribute : ActionFilterAttribute 
	{
		private IUnitOfWork _work;

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			_work = UnitOfWork.Begin();

			base.OnActionExecuting(filterContext);
		}

		public override void OnResultExecuted(ResultExecutedContext filterContext)
		{
			base.OnResultExecuted(filterContext);

			try
			{
				if ((filterContext.Exception != null) && (!filterContext.ExceptionHandled))
				{
					_work.Rollback();
				}
				else
				{
					_work.Commit();
				}
			}
			finally
			{
				UnitOfWork.DisposeOfUnitOfWork(_work);
			}
		}
	}
}
